//
//  ViewController.m
//  YY键盘
//
//  Created by hu on 16/5/27.
//  Copyright © 2016年 hu. All rights reserved.
//
#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"[函数名:%s]\n" "[行号:%d] \n" fmt), __FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...);
#endif
#import "ViewController.h"
#import "GWChatInputView.h"
#import "SecondViewController.h"
#import "HUChatTextView/HUFace/HUFaceManager.h"
#import "Mp3Recorder.h"
#import <AVFoundation/AVFoundation.h>
#import "YYText.h"
#import "HUFaceManager.h"
#import "UIScrollView+Pages.h"
#import "WebViewController.h"

@interface HUTableView : UITableView <UIScrollViewDelegate>
@property (nonatomic, weak) GWChatInputView* chatInputView;
@end
@implementation HUTableView


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.chatInputView endInputing];
}

@end
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,GWChatBarDelegate,AVAudioPlayerDelegate>
{
    UIButton* _button;
}
@property (nonatomic, strong) NSMutableArray* messageArray;
@property (nonatomic, weak) GWChatInputView* textView;
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, weak) YYLabel* label ;
@end

@implementation ViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.textView) {
        [self.textView endInputing];
        [self.textView show];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.textView hide];
    [self.textView endInputing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0 green:147/255. blue:1 alpha:1];
    // Do any additional setup after loading the view, typically from a nib.
    

    
    self.messageArray = [[NSMutableArray alloc]initWithCapacity:0];
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationLaunchOptionsAnnotationKey]];


    CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - KMinHeight);
    HUTableView *tableView = [[HUTableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    tableView.backgroundColor = [UIColor clearColor];
    tableView.delegate = self;
    tableView.dataSource =self;
    [tableView setContentOffset:CGPointMake(0, 0) animated:NO];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:tableView];

    self.tableView = tableView;
    [self.view addSubview:tableView];

    GWChatInputView *textView = [GWChatInputView shareManager];
    textView.type = 3;
    textView.delegate = self ;
    textView.viewController = self ;
    [textView show];
    tableView.chatInputView = textView;
    self.textView = textView;
    
    YYLabel* label = [[YYLabel alloc]init];
    label.frame = CGRectMake(0, SCREEN_HEIGHT / 3, SCREEN_WIDTH, 60);
    label.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:label];
    label.numberOfLines = 0;
    self.label = label;

    
    NSString* text = @"www.baidu.cn http://baidu.com https://www.baidu.com  [委屈]";
    self.label.attributedText = [GWChatInputView emotionStrWithString:text URLBlock:^(NSString *content, NSUInteger type) {
        if (type == 0) {
            //TODO: type == 0 是网站 判断是否包含http 不包含需要加上去
            WebViewController * webView = [[WebViewController alloc]init];
            if (![content containsString:@"http"]) {
                content = [@"http://" stringByAppendingString:content];
            }
            webView.URL = content;
            GWChatInputView* object = [GWChatInputView shareManager];
            [object.viewController.navigationController pushViewController:webView animated:YES];
        }
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell;

    cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell" ];
    }
    cell.textLabel.text = _messageArray[indexPath.row];
    cell.backgroundColor = [UIColor lightGrayColor];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString* string = [_messageArray objectAtIndex:indexPath.row];
    
    NSData* data = [NSData dataWithContentsOfFile:string];
    if (!data) {
        return;
    }
    [self.textView playVoiceFile:data];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  {
    return _messageArray.count;
}
- (void)chatBar:(GWChatInputView *)chatBar sendVoice:(NSString *)voiceFileName seconds:(NSTimeInterval)seconds {
    NSString* string = [NSString stringWithFormat:@"%@",voiceFileName];
    [_messageArray addObject:string];
    [_tableView reloadData];

}
- (void)chatBar:(GWChatInputView *)chatBar sendMessage:(NSString *)message {
    [self.messageArray addObject:message];
    [self.tableView reloadData];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:_messageArray.count - 1 inSection:0];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

}

- (void)chatBar:(GWChatInputView *)chatBar sendPictures:(NSArray *)pictures {
//    NSLog(@"%@",[pictures firstObject]);
    [_messageArray addObject:@"图片"];
    [_tableView reloadData];
}
- (void)chatBarStartVedio {
    [_messageArray addObject:@"视频聊天"];
    [_tableView reloadData];
}
- (void)chatBarSendCase {
    [_messageArray addObject:@"病例"];
    [_tableView reloadData];
}
/**
 *  开始编辑
 *
 *  @param textView 输入框
 */
- (void)chatBarTextViewDidBeginEditing:(HPGrowingTextView *)textView {
//    DLog(@"开始编辑");
}
/**
 *  结束编辑
 *
 *  @param textView 输入框
 */
- (void)chatBarTextViewDidEndEditing:(HPGrowingTextView *)textView {
//    DLog(@"结束编辑");
}
/**
 *  改变编辑状态
 *
 *  @param textView 输入框
 */
- (void)chatBarTextViewDidChangeEditing:(HPGrowingTextView *)textView {
//    DLog(@"改变编辑");
}
- (void)chatBarGrowingTextViewEditing:(HPGrowingTextView *)textView {
//    DLog(@"输入框高度改变");
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    
//    DLog(@"播放完成，time ===== %f, flag ===== %o",player.duration,flag);
}
- (void)chatBarChangeHeight:(CGFloat)changeHeight toType:(GWFunctionViewShowType)toType {
    CGRect frame = self.tableView.frame;
    frame = CGRectMake(0, frame.origin.y + changeHeight, frame.size.width, frame.size.height);
    [UIView  animateWithDuration:0.25 animations:^{

        self.tableView.frame = frame;
    }];
    

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.tableView.isDragging) {
        [self.textView endInputing];
    }
}
- (NSAttributedString *)httpURL:(NSMutableAttributedString *)text withRange:(NSRange)range{
    NSMutableAttributedString *one = text;
    one.yy_font = [UIFont systemFontOfSize:16];
    
    [one yy_setTextHighlightRange:range
                            color:[UIColor colorWithRed:0.093 green:0.492 blue:1.000 alpha:1.000]
                  backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.220]
                        tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                            NSString* string = [text.string substringWithRange:range];
                            NSLog(@"%@",string);
                        }];
    
    return one;
}
- (NSArray *) getHttpURLFromString:(NSString *) str {
    
    NSError* error = nil;
    //        NSString* regulaStr = @"(\\w+)://([^/:]+)(:\\d*)?([^#\\s]*)";
    NSString* regulaStr = @"(^(((ht|f)tp(s?))\\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\\-\\.]+\\.(com|cn|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\\\,\\;\\?\\'\\\\+&amp;%\\$#\\=~_\\-]+))*$)|((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|((((http[s]{0,1}|ftp)://)?((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))(\\:[0-9]+)(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    NSArray *arrayOfAllMatches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])];
    NSMutableArray* numbers = [NSMutableArray arrayWithCapacity:arrayOfAllMatches.count];
    for (NSTextCheckingResult *match in arrayOfAllMatches)
    {
        NSString* substringForMatch = [str substringWithRange:match.range];
        [numbers addObject:substringForMatch];
        
    }
    
    return numbers;
}
@end
